package vn.com.vhc.babyui;

import vn.com.vhc.library.Uptimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
	String strSleep;
	private long elapsedTime;
	private long currentTime;
	private final int REFRESH_RATE = 10;

	
	Button btnSleep;
	private Handler mHandler = new Handler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnSleep = (Button)findViewById(R.id.btnSleep);
	}

	public void btnSleep(View view) {
		Intent i = new Intent(getApplication(), SleepActivity.class);
		if(!btnSleep.getText().toString().contains("Sleep"))
			i.putExtra("TIME_SLEEP", btnSleep.getText().toString());
		startActivity(i);
	}
	@Override
	protected void onStart() {
		
		super.onStart();
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null)
		{
			strSleep = bundle.getString("TIME_SLEEP");
			String[] str = strSleep.split(":");
			currentTime =System.currentTimeMillis()- (Long.parseLong(str[0])*60*60*1000 + Long.parseLong(str[1])*1000*60 +  Long.parseLong(str[2])*1000);
			
			mHandler.removeCallbacks(startTimer);
	        mHandler.postDelayed(startTimer, 0);
		}
		
	}
	private Runnable startTimer = new Runnable() {
		   public void run() {
			   elapsedTime = System.currentTimeMillis()-currentTime;
			   btnSleep.setText(new Uptimer().updateTimer(elapsedTime));
			   mHandler.postDelayed(this,REFRESH_RATE);
			}
		};
	@Override
	protected void onStop() {
		super.onStop();
		finish();
	}
}
